import { defineEventHandler, getQuery, createError, setCookie, sendRedirect } from "h3";
import { UserService } from "../../../services/userService";
import { signJWT } from "../../../utils/jwt";

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const { code } = query;

  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Authorization code is required",
    });
  }

  const config = useRuntimeConfig();

  try {
    // 交换授权码获取访问令牌
    const tokenResponse = await $fetch("https://github.com/login/oauth/access_token", {
      method: "POST",
      headers: {
        Accept: "application/json",
      },
      body: {
        client_id: config.githubClientId,
        client_secret: config.githubClientSecret,
        code,
      },
    });

    // 获取用户信息
    const userInfo = await $fetch("https://api.github.com/user", {
      headers: {
        Authorization: `Bearer ${tokenResponse.access_token}`,
        "User-Agent": "Mindweaver",
      },
    });

    // 获取用户邮箱
    const emails = await $fetch("https://api.github.com/user/emails", {
      headers: {
        Authorization: `Bearer ${tokenResponse.access_token}`,
        "User-Agent": "Mindweaver",
      },
    });

    const primaryEmail = emails.find((email) => email.primary)?.email;

    let user = await UserService.findByGithubId(userInfo.id.toString());

    if (!user && primaryEmail) {
      // 检查是否已有相同邮箱的用户
      const existingUser = await UserService.findByEmail(primaryEmail);
      if (existingUser) {
        // 关联GitHub账号
        user = await UserService.updateUser(existingUser.id, {
          githubId: userInfo.id.toString(),
          avatar: userInfo.avatar_url,
        });
      } else {
        // 创建新用户
        user = await UserService.createUser({
          email: primaryEmail,
          name: userInfo.name || userInfo.login,
          githubId: userInfo.id.toString(),
          avatar: userInfo.avatar_url,
        });
      }
    }

    if (!user) {
      throw new Error("Unable to create or find user");
    }

    const token = signJWT({ userId: user.id, email: user.email });

    setCookie(event, "auth-token", token, {
      httpOnly: true,
      secure: true,
      sameSite: "strict",
      maxAge: 60 * 60 * 24 * 7, // 7 days
    });

    // 重定向到前端
    return sendRedirect(event, `${config.public.frontendUrl}/auth/callback?success=true`);
  } catch (error) {
    console.error("GitHub OAuth error:", error);
    return sendRedirect(event, `${config.public.frontendUrl}/auth/callback?error=oauth_failed`);
  }
});